<?php

class TranslateController extends AdminController {

    const MODEL_CLASS_NAME = 'Profile';       

    public function actionIndex($id) {
	    $model = $this->loadModel();
		$model = $model[0];
		$translatedModel = $this->loadTranslatedModel();

		if($translatedModel == null){ //There is no translated model so, create new profile for translate
			$translatedModel = $this->createTranslatedModel($id, $model);
		}else{//The translated model is existing so create a new profile for translate
			$translatedModel = $translatedModel[0];
			$translatedModel = $this->updateTranslatedModel($id, $translatedModel, $model);
		}
		if (isset($_POST[TranslateController::MODEL_CLASS_NAME][1])){
			$this->showMessage(MsgType::SUCCESS, t('MSG_INFO_SAVE_TRANSLATED_PROFILE_SUCCESS', 'messages' , array('{0}' => t('LBL_PROFILE', 'profile'))));
			if (isset($_POST["cmsTask"])) {
				$cmsTask = $_POST["cmsTask"];
				switch ($cmsTask) {
					case ActionType::SAVE: {
						$url = url($this->id . '/index', array('id'=>$model->id));
						$this->redirect($url);
						break;
					}
					case ActionType::SAVE_CLOSE: {
						$this->redirect(url('/profile/'));
						break;
					}
					case ActionType::SUBMIT: {
						$this->redirect(url('/profile/'));
						break;
					}
				}
			}
			app()->end();
		}else{
			$this->render('translate', array('model' => $model, 'translatedModel' => $translatedModel));
		}
    }  

    public function loadDetailProfile(){
    	$model = null;
    	if (isset($_GET['id'])) {
    		$ids = explode(',', $_GET['id']);
    		if (isset($ids)) {
    			$criteria = new CDbCriteria;
    			$criteria->addInCondition('t.id', $ids);
    			$model = Profile::model()->with('family');
    			$model = Profile::model()->with('workingProcesses');
    			$model = Profile::model()->with(array('advanceProfile' => array('with' => array('hiringCompany'))));
    			$model = Profile::model()->with(array('academy' => array('with' => array('studyingProcesses'))))->findAll($criteria);
    		}
    	}
    	return $model;
    }
    
    public function loadModel() {
    	$model = null;
    	if (isset($_GET['id'])) {
    		$ids = explode(',', $_GET['id']);
    		if (isset($ids)) {
    			$criteria = new CDbCriteria;
    			$criteria->addInCondition('t.id', $ids);    			
    			$model = Profile::model()->with('family');
    			$model = Profile::model()->with('workingProcesses');
    			$model = Profile::model()->with(array('academy' => array('with' => array('studyingProcesses'))))->findAll($criteria);
    		}
    	}
    	return $model;
    }
    
    public function loadTranslatedModel() {
    	$model = null;
    	if (isset($_GET['id'])) {
    		$ids = explode(',', $_GET['id']);
    		if (isset($ids)) {
    			$criteria = new CDbCriteria;
    			$criteria->addInCondition('t.related_id', $ids);
    			$criteria->compare('t.language', 'JP');
    			$model = Profile::model()->with('family');
    			$model = Profile::model()->with('workingProcesses');
    			$model = Profile::model()->with(array('academy' => array('with' => array('studyingProcesses'))))->findAll($criteria);
    		}
    	}
    	return $model;
    }
    
    public function createTranslatedModel($id, $vnModel){
    	$model = new Profile('create');    	
    	//Set value to missing field and reset values of translated fields.    	
		if (method_exists($model, 'unsetAttributes')) {
			$model->unsetAttributes();
		}		
		
		$model->family = new Family('create');
		$model->academy = new Academy('create');
		
		if (method_exists($model->family, 'unsetAttributes')) {
			$model->family->unsetAttributes();
		}
		if (method_exists($model->academy, 'unsetAttributes')) {
			$model->academy->unsetAttributes();
		}

		//create studying process with the same number of VN profile
		if ($model->academy !=null) {
			$tmp = array();
			foreach ($vnModel->academy->studyingProcesses as $vnProcess){
				if($this->isAllAttributesEmpty($vnProcess) == FALSE){
					$process = new StudyingProcess();
					$process->unsetAttributes();
					array_push($tmp, $process);
				}
			}
			$model->academy->studyingProcesses = $tmp; //Create a new item
		}
		 
		if ($model !=null) {
			$workTmp = array();
			foreach ($vnModel->workingProcesses as $vnWorkingProcess){
				if($this->isAllAttributesEmpty($vnWorkingProcess) == FALSE){
					$work = new WorkingProcess();
					$work->unsetAttributes();
					array_push($workTmp, $work);
				}
			}				
			$model->workingProcesses = $workTmp; //Create a new item
		}
    	
    	
    	if (isset($_POST[TranslateController::MODEL_CLASS_NAME][1])) {
    		//Copy attributes from profile VN to foreign language profile
    		$model->attributes = $vnModel->attributes;//$_POST[TranslateController::MODEL_CLASS_NAME][0];
			$model->related_id = $id;
			$model->language = ProfileLanguage::JP;
			
    		//Set attributes on form to foreign language profile
    		foreach (array_keys($_POST[TranslateController::MODEL_CLASS_NAME][1]) as $att){
    			$model[$att] = $_POST[TranslateController::MODEL_CLASS_NAME][1][$att];
    		}   
			
    		if ($vnModel->status != ProfileStatus::STATUS_NEW){
    			$model->status = ProfileStatus::STATUS_TRANSLATING;
    		}
			//Update status if user submit
			if(isset($_POST["cmsTask"]) && $_POST["cmsTask"] == ActionType::SUBMIT){
				$model->status = ProfileStatus::STATUS_TRANSLATED;				
				$vnModel->status = ProfileStatus::STATUS_TRANSLATED;
			}else if ($vnModel->status != ProfileStatus::STATUS_NEW){
				$vnModel->status = ProfileStatus::STATUS_TRANSLATING;
			}
			
			//Update health checking
			$vnModel->is_pass_health_checking = $_POST[TranslateController::MODEL_CLASS_NAME][0]['is_pass_health_checking'];
			$vnModel->type_of_power = $_POST[TranslateController::MODEL_CLASS_NAME][0]['type_of_power'];
			$vnModel->health_checking_date = $_POST[TranslateController::MODEL_CLASS_NAME][0]['health_checking_date'];
			$vnModel->type_of_health = $_POST[TranslateController::MODEL_CLASS_NAME][0]['type_of_health'];
			$vnModel->do_forward_profile = $_POST[TranslateController::MODEL_CLASS_NAME][0]['do_forward_profile'];
			if(isset($vnModel->health_checking_date) && $vnModel->health_checking_date != NULL){
				$date = DateTime::createFromFormat ( 'd-m-Y', $vnModel->health_checking_date);
				$vnModel->health_checking_date = $date->format ( 'Y-m-d' );
			}else{
				$vnModel->health_checking_date = NULL;
			}
			
			//Save VN profile for Health checking result
			$vnModel->scenario = Profile::SCENARIO_UPDATE;
			$vnModel->saveAttributes(array('status', 'is_pass_health_checking','type_of_power', 
			'health_checking_date', 'type_of_health', 'do_forward_profile'));
			
    		// Save only if model validates
    		if ($model->validate()) {
    			if ($model->save(true)) {
    				//Copy family attributes from profile VN to foreign language profile
    				$model->family->attributes = $vnModel->family->attributes;
    				$model->family->profile_id = $model->id;    				    				    				    			
    				foreach (array_keys($_POST['Family'][1]) as $familyAtt){
    					$model->family[$familyAtt] = $_POST['Family'][1][$familyAtt];
    				}
    				
    				$model->academy->attributes = $_POST['Academy'][1];
    				$model->academy->profile_id = $model->id;
    				// If callback is set run additional processing
    				if ($model->family->validate() && $model->academy->validate()){
    					$model->family->save(true);
    					//Check and save academy
    					if($this->isAllAttributesEmpty($vnModel->academy->attributes)==FALSE){
    						$model->academy->save(true);
    					}
    					//check and add new studyprocesses
    					if(isset($_POST['StudyingProcess'][1])){
	    					foreach($_POST['StudyingProcess'][1] as $j => $submittedprocess){
	    						$studyingProcesses = new StudyingProcess('create');
	    						$studyingProcesses->academy_id = $model->academy->id;
	    						$studyingProcesses->attributes = $submittedprocess;
	    						if ($studyingProcesses->validate()){
	    							$studyingProcesses->language = ProfileLanguage::JP;
	    							$studyingProcesses->related_id = $vnModel->academy->studyingProcesses[$j]->id;
	    							$studyingProcesses->save();
	    						}
	    					}
    					}
    	
    					//check and add new workingprocesses
    					if(isset($_POST['WorkingProcess'][1])){
    						foreach($_POST['WorkingProcess'][1] as $n => $submittedwork){
    							$workProcess = new WorkingProcess('create');
    							$workProcess->profile_id = $model->id;
    							$workProcess->attributes = $submittedwork;
    							if ($workProcess->validate()){
    								$workProcess->language = ProfileLanguage::JP;
    								$workProcess->related_id = $vnModel->workingProcesses[$n]->id;
    								$workProcess->save();
    							}
    						}
    					}    					
    				}
    			}
    		}
    	}
    	return $model;
    }
    
    public function updateTranslatedModel($id, $model, $vnModel){
    	if (isset($_POST[TranslateController::MODEL_CLASS_NAME][1])) {
    		//Keep track model before update to save log.
    		$oldModel = $this->loadTranslatedModel();
    		$oldModel = $oldModel[0];
    		// Format date to the same format with new profile
    		$date = DateTime::createFromFormat ( 'd-m-Y', $oldModel->birth_date );
    		$oldModel->birth_date = $date->format ( 'Y-m-d' );
    		
    		// Get input data
    		$model->attributes = $_POST[TranslateController::MODEL_CLASS_NAME][1];   
    		if ($vnModel->status != ProfileStatus::STATUS_NEW){ 		
    			$model->status = ProfileStatus::STATUS_TRANSLATING;
    		}
			//Update status if user submit
			if(isset($_POST["cmsTask"]) && $_POST["cmsTask"] == ActionType::SUBMIT){
				$model->status = ProfileStatus::STATUS_TRANSLATED;				
				$vnModel->status = ProfileStatus::STATUS_TRANSLATED;
			}else if ($vnModel->status != ProfileStatus::STATUS_NEW){
				$vnModel->status = ProfileStatus::STATUS_TRANSLATING;
			}
			
			//Update health checking
			$vnModel->is_pass_health_checking = $_POST[TranslateController::MODEL_CLASS_NAME][0]['is_pass_health_checking'];
			$vnModel->type_of_power = $_POST[TranslateController::MODEL_CLASS_NAME][0]['type_of_power'];
			$vnModel->health_checking_date = $_POST[TranslateController::MODEL_CLASS_NAME][0]['health_checking_date'];
			$vnModel->type_of_health = $_POST[TranslateController::MODEL_CLASS_NAME][0]['type_of_health'];
			$vnModel->do_forward_profile = $_POST[TranslateController::MODEL_CLASS_NAME][0]['do_forward_profile'];
			if(isset($vnModel->health_checking_date) && $vnModel->health_checking_date != NULL){
				$date = DateTime::createFromFormat ( 'd-m-Y', $vnModel->health_checking_date);
				$vnModel->health_checking_date = $date->format ( 'Y-m-d' );
			}else{
				$vnModel->health_checking_date = NULL;
			}
			
			
			$vnModel->scenario = Profile::SCENARIO_UPDATE;
			$vnModel->saveAttributes(array('status', 'is_pass_health_checking','type_of_power', 
			'health_checking_date', 'type_of_health', 'do_forward_profile'));
			
    		$model->family->attributes = $_POST['Family'][1];
    		$model->academy->attributes = $_POST['Academy'][1];
    		$model->scenario = 'update';
    	
    		$vnModel->updated_fields = $this->update_changed_attributes($oldModel, $vnModel);
    		
    		// Save only if model validates
    		if ($model->validate()) {
    			// Save the model
    			if ($model->save(true)) {    				
    				$model->family->profile_id = $model->id;
    				$model->academy->profile_id = $model->id;
    				if ($model->family->validate()&& $model->academy->validate()){
    					$model->family->save();
    					//save academy    					
    					//Check and save academy
    					if($this->isAllAttributesEmpty($vnModel->academy->attributes)==FALSE || $model->academy->isNewRecord == FALSE){
    						$model->academy->save(true);
    					}
    					
    					//Update old studyprocesses
    					foreach($model->academy->studyingProcesses as $i => $process){
    						if(isset($_POST['StudyingProcess'][1]) && isset($_POST['StudyingProcess'][1][$i])){
    							$vnStudyingProcess = $vnModel->academy->studyingProcesses[$i];
    							$changed_fields = $this->update_changed_studyingprocess_attributes($process, $_POST['StudyingProcess'][1][$i], $vnStudyingProcess);
    							$process->attributes = $_POST['StudyingProcess'][1][$i];
    							$vnStudyingProcess->updated_fields = $changed_fields;
    							$process->academy_id = $model->academy->id;
    							$process->save();
    							$vnStudyingProcess->save();
    						}else{
    							$process->delete();
    						}
    					}
    					//check and add new studyprocesses
    					if(isset($_POST['StudyingProcess'][1])){
    						foreach($_POST['StudyingProcess'][1] as $j => $submittedprocess){
    							if(array_key_exists($j,$model->academy->studyingProcesses) == FALSE){
    								$studyingProcesses = new StudyingProcess('create');
    								$studyingProcesses->academy_id = $model->academy->id;
    								$studyingProcesses->attributes = $_POST['StudyingProcess'][1][$j];
    								if ($studyingProcesses->validate()){
    									$studyingProcesses->save();
    								}
    							}
    						}
    					}
    	
    					//Update working process
    					foreach($model->workingProcesses as $m => $work){
    						if(isset($_POST['WorkingProcess'][1]) && isset($_POST['WorkingProcess'][1][$m])){
    							$vnWork = $vnModel->workingProcesses[$m];
    							$changed_fields = $this->update_changed_workingprocess_attributes($work, $_POST['WorkingProcess'][1][$m], $vnWork);
    							$work->attributes = $_POST['WorkingProcess'][1][$m];
    							$vnWork->updated_fields = $changed_fields;
    							$work->profile_id = $model->id;
    							$work->save();
    							$vnWork->save();
    						}else{
    							$work->delete();
    						}
    					}
    					//check and add new workingprocesses
    					if(isset($_POST['WorkingProcess'][1])){
    						foreach($_POST['WorkingProcess'][1] as $n => $submittedwork){
    							if(array_key_exists($n,$model->workingProcesses) == FALSE){
    								$workProcess = new WorkingProcess('create');
    								$workProcess->profile_id = $model->id;
    								$workProcess->attributes = $submittedwork;
    								if ($workProcess->validate()){
    									$workProcess->save();
    								}
    							}
    						}
    					}    	    	    					    					
    				}
    				//Update updated_fields which was translated.
    				$vnModel->scenario = Profile::SCENARIO_UPDATE;
    				$vnModel->saveAttributes(array('updated_fields'));
    				
    				//Save history to database
    				$dataLogger = new DataLogger();
    				$dataLogger->recordProfileChanges($oldModel, $model);
    			}
    		}
    	}
    	return $model;
    }
    
    public function isAllAttributesEmpty($attributes){
    	foreach($attributes as $att){
    		if ((is_array($att)) || ($att instanceof Traversable))
    		{
    			return $this->isAllAttributesEmpty($att);
    		}else{
    			if($att != ''){
    				return FALSE;
    			}
    		}
    	}
    	return TRUE;
    }
    
    public function actionReject($id)
    {
    	$this->_changeStatus($id, ProfileStatus::STATUS_REJECTED);
    }
    
    public function actionRetranslate($id)
    {
    	$this->_changeStatus($id, ProfileStatus::STATUS_WAITING_FOR_RETRANSLATE);
    }
    
    public function actionAccept($id)
    {
    	$this->_changeStatus($id, ProfileStatus::STATUS_ACCEPTED);
    }
    
    public function _changeStatus($id, $status) {
    	$model = Profile::model()->findByPk($id);
    	$model->status = $status;
    	$model->scenario = Profile::SCENARIO_UPDATE;
    	
    	$isSuccess = $model->saveAttributes(array('status'));
    	
    	if($isSuccess){
    		
	    	$criteria = new CDbCriteria;
	    	$criteria->compare('t.related_id', $id);
	    	$criteria->compare('t.language', 'JP');
	    	$translatedModel = Profile::model()->findAll($criteria);
	    	if($translatedModel != null)
	    	{
		    	$translatedModel = $translatedModel[0];
		    	$translatedModel->status = $status;
		    	$isSuccess = $translatedModel->saveAttributes(array('status'));    	
	    	}    		
    	}
    	
    	if($isSuccess)
    	{
    		$this->showMessage(MsgType::SUCCESS, t('MSG_SUCCESS', 'messages' , array('{0}'=>'Thay đổi trạng thái', '{1}' => t('LBL_PROFILE', 'profile'))));
    	}
    	else
    	{
    		$this->showMessage(MsgType::ERROR, t('MSG_INFO_ERROR', 'messages' , array('{1}'=>'thay đổi trạng thái', '{0}' => t('LBL_PROFILE', 'profile'))));
    	}
    	$this->redirect(url('/profile/'));
    }
    
    public function actionDetail($id){
    	$model = $this->loadDetailProfile();
    	$model = $model[0];
    	$translatedModel = $this->loadTranslatedModel();    	
    	if(!empty($translatedModel))
    	{    	
    		$translatedModel = $translatedModel[0];
    	}
    	else {
    		$translatedModel = null;
    	}
    	$this->render('view', array(
    			'model' => $model, 'translatedModel'=>$translatedModel));
    }
    
    public function actionPrint($id)
    {
    	$model = $this->loadModel();
    	$model = $model[0];
    	$translatedModel = $this->loadTranslatedModel();
		if (count($translatedModel) > 0) {
			$translatedModel = $translatedModel[0];
		}
		else{
			$translatedModel = NULL;
		}

    	$this->layout = 'print';
    	$this->render('print', array(
    			'model' => $model, 'translatedModel'=>$translatedModel));
    }
    
    private function update_changed_attributes($oldProfile, $vnProfile){
    	#Keep track updated fields
    	$changed_fields = array();
    	if($vnProfile->updated_fields != NULL)
    		$changed_fields = explode(',', $vnProfile->updated_fields);
    
    	//Basic info
    	foreach($_POST[TranslateController::MODEL_CLASS_NAME][1] as $i => $attProfile){
    		$key = array_search($i, $changed_fields);
    		if($attProfile != $oldProfile->attributes[$i] && $key !== FALSE){
    			unset($changed_fields[$key]);
    		}
    	}
    	//Family info
    	foreach($_POST['Family'][1] as $j => $attProfile){
    		$key = array_search($j, $changed_fields);
    		if($attProfile != $oldProfile->family->attributes[$j] &&  $key !== FALSE){
    			unset($changed_fields[$key]);
    		}
    	}
    
    	//Academy info
    	foreach($_POST['Academy'][1] as $k => $attProfile){
    		$key = array_search($k, $changed_fields);
    		if($attProfile != $oldProfile->academy->attributes[$k] &&  $key !== FALSE){
    			unset($changed_fields[$key]);
    		}
    	}
    	
    	if (count($changed_fields) > 0)
    		return implode(',', $changed_fields);
    	else
    		return NULL;
    }
    
    private function update_changed_studyingprocess_attributes($studyingProcess, $postData, $vnStudyingProcess){
    	#Keep track updated fields
    	$changed_fields = array();
    	if($vnStudyingProcess->updated_fields != NULL)
    		$changed_fields = explode(',', $vnStudyingProcess->updated_fields);
    	
    	//Basic info
    	foreach($postData as $i => $attProfile){
    		$key = array_search($i, $changed_fields);
    		if($attProfile != $studyingProcess->attributes[$i] && $key !== FALSE){
    			unset($changed_fields[$key]);
    		}
    	}
    	
    	if (count($changed_fields) > 0)
    		return implode(',', $changed_fields);
    	else
    		return NULL;
    }
    
    private function update_changed_workingprocess_attributes($workingProcess, $postData, $vnWorkingProcess){
    	#Keep track updated fields
    	$changed_fields = array();
    	if($vnWorkingProcess->updated_fields != NULL)
    		$changed_fields = explode(',', $vnWorkingProcess->updated_fields);
    	 
    	//Basic info
    	foreach($postData as $i => $attProfile){
    		$key = array_search($i, $changed_fields);
    		if($attProfile != $workingProcess->attributes[$i] && $key !== FALSE){
    			unset($changed_fields[$key]);
    		}
    	}
    	 
    	if (count($changed_fields) > 0)
    		return implode(',', $changed_fields);
    	else
    		return NULL;
    }   
    
	public function actionReport(){    	
		if (isset($_GET['id'])) {
			$id = $_GET['id'];
			$model = Profile::model()->findByPk($id);
		}
		$this->render('report', array('model' => $model));	
    }
    
	public function actionSaveReport($id){
		try {
		Yii::import('ext.PHPWord.**', true);
    	$model = $this->loadDetailProfile();
    	
    	$filename = $_GET['f'];
    	$ext = $_GET['ext'];
    	
    	if(count($model) > 0)
    		$model = $model[0];
	    	$PHPWord = new PHPWord();
	    
	    	$document = $PHPWord->loadTemplate(MEDIA_FOLDER . '/files/' . $filename . '.' . $ext);	    	
	    	
	    	//Parse full name to firstname and lastname
	    	$full_name = $model->full_name;
	    	$parts = explode(" ", $full_name);
	    	$first_name = $parts[count($parts) - 1];
	    	$last_name = $parts[0];
	    	$middle_name_parts = array_slice($parts, 1, count($parts) - 2);
	    	$middle_name = implode(' ', $middle_name_parts);
	    	
	    	//get day, month,year from birth_day
	    	$birth_day = date('d', strtotime($model->birth_date));
	    	$birth_month = date('m', strtotime($model->birth_date));
	    	$birth_year = date('Y', strtotime($model->birth_date));
	    	
	    	//get day, month,year from id_card
	    	$id_card_date = $id_card_day = $id_card_month = $id_card_year = '';
	    	//get day, month,year from passport
	    	$passport_date = $passport_day = $passport_month = $passport_year = '';
	    	
	    	if(isset($model->advanceProfile))
	    	{
	    		$id_card_date = $model->advanceProfile->id_card_provided_date;
		    	$id_card_day = date('d', strtotime($id_card_date));
		    	$id_card_month = date('m', strtotime($id_card_date));
		    	$id_card_year = date('Y', strtotime($id_card_date));
		    	
		    	$passport_date = $model->advanceProfile->passport_provided_date;
		    	$passport_day = date('d', strtotime($passport_date));
		    	$passport_month = date('m', strtotime($passport_date));
		    	$passport_year = date('Y', strtotime($passport_date));
	    	}
	    	
	    	$document->setValue('HO_TEN', $full_name);
	    	$document->setValue('HO', $last_name);
	    	$document->setValue('TEN_LOT', $middle_name);
	    	$document->setValue('TEN', $first_name);
	    	$document->setValue('NGAY_SINH', $birth_day);
	    	$document->setValue('THANG_SINH', $birth_month);
	    	$document->setValue('NAM_SINH', $birth_year);
	    	$document->setValue('NGAY_THANG_NAM_SINH', $model->birth_date);
	    	$document->setValue('GIOI_TINH', ($model->sex == 1) ? 'Nam' : 'Nữ');
			$document->setValue('NOI_SINH', $model->province->province_name);
			$document->setValue('DIEN_THOAI', $model->phone_number);
			$document->setValue('DIA_CHI', $model->address);
			
			$document->setValue('MA_HO_SO', $model->advanceProfile->code);
			$document->setValue('CMND', $model->advanceProfile->id_card_number);
			$document->setValue('NGAY_THANG_NAM_CAP_CMND', $id_card_date);
			$document->setValue('NGAY_CAP_CMND', $id_card_day);
			$document->setValue('THANG_CAP_CMND', $id_card_month);
			$document->setValue('NAM_CAP_CMND', $id_card_year);
			$document->setValue('NOI_CAP_CMND', $model->advanceProfile->id_card_provided_place);
			
			$document->setValue('HO_CHIEU', $model->advanceProfile->passport_number);
			$document->setValue('NGAY_THANG_NAM_CAP_HO_CHIEU', $passport_date);
			$document->setValue('NGAY_CAP_HO_CHIEU', $passport_day);
			$document->setValue('THANG_CAP_HO_CHIEU', $passport_month);
			$document->setValue('NAM_CAP_HO_CHIEU', $passport_year);			
			$document->setValue('NOI_CAP_HO_CHIEU', $model->advanceProfile->passport_provided_place);
			
			$document->setValue('GHI_CHU', $model->advanceProfile->note);
			
			$document->setValue('TEN_CHA', $model->family->father_name);
			$document->setValue('TEN_ME', $model->family->mother_name);
			$document->setValue('NHOM_MAU', $model->blood_group);
			$document->setValue('CHIEU_CAO', $model->height);
			$document->setValue('CAN_NANG', $model->weight);
			$document->setValue('GHI_CHU_SUC_KHOE', ($model->is_pass_health_checking == 1) ? 'Đạt' : 'Không đạt');
			$document->setValue('NGAY_KHAM_SUC_KHOE', $model->health_checking_date);
			$document->setValue('NGAY_NOP_HO_SO', $model->advanceProfile->apply_date);
			$document->setValue('NGAY_TRUNG_TUYEN', $model->advanceProfile->selected_date);
			$document->setValue('DON_HANG', $model->advanceProfile->order);
			$document->setValue('THOI_HAN_HOP_DONG', $model->advanceProfile->contract_duration);
			$document->setValue('MA_CONG_TY_TIEP_NHAN', $model->advanceProfile->hiringCompany->code);
			$document->setValue('TEN_CONG_TY_TIEP_NHAN', $model->advanceProfile->hiringCompany->name);
			$document->setValue('DIA_CHI_CONG_TY_TIEP_NHAN', $model->advanceProfile->hiringCompany->address);
			$document->setValue('GIAM_DOC_CONG_TY_TIEP_NHAN', $model->advanceProfile->hiringCompany->director);
			
			$document->setValue('TEN_NGHIEP_DOAN', $model->advanceProfile->hiringCompany->union->name);
			$document->setValue('DIA_CHI_NGHIEP_DOAN', $model->advanceProfile->hiringCompany->union->address);
			$document->setValue('SO_DIEN_THOAI_NGHIEP_DOAN', $model->advanceProfile->hiringCompany->union->phone_number);
			$document->setValue('CHU_TICH_NGHIEP_DOAN', $model->advanceProfile->hiringCompany->union->president);
			$document->setValue('LUONG', $model->advanceProfile->salary);
			$document->setValue('TRO_CAP', $model->advanceProfile->hiringCompany->first_month_allowance);
			$document->setValue('PHI_MOI_GIOI', $model->advanceProfile->introducing_fee);
			$document->setValue('NGAY_XUAT_CANH', $model->advanceProfile->go_date);
			$document->setValue('DIA_CHI_TREN_VISA', $model->advanceProfile->visa_address);
			$document->setValue('THANH_PHO_DEN', $model->advanceProfile->arrive_city);
			$document->setValue('CHUYEN_BAY', $model->advanceProfile->flight);
			$document->setValue('MA_CONG_TY_TIEN_CU', $model->advanceProfile->introducingCompany->code);
			$document->setValue('TEN_CONG_TY_TIEN_CU', $model->advanceProfile->introducingCompany->name);
			$document->setValue('DIA_CHI_CONG_TY_TIEN_CU', $model->advanceProfile->introducingCompany->address);
			$document->setValue('NGUOI_DAI_DIEN_CONG_TY_TIEN_CU', $model->advanceProfile->introducingCompany->representative);
			$document->setValue('SO_DIEN_THOAI_CONG_TY_TIEN_CU', $model->advanceProfile->introducingCompany->phone_number);
			$document->setValue('SO_HD_PHAI_CU', $model->advanceProfile->contract_number);
			$document->setValue('VE_TRUOC_HAN_HOP_DONG', $model->advanceProfile->back_date_before_contract);
			$document->setValue('CONG_TY_PHAI_CU', $model->advanceProfile->dispatching_company);
			$document->setValue('CONG_TY_PHAI_CU_NGHIEP_DOAN', $model->advanceProfile->hiringCompany->union->dispatched_company);
			$document->setValue('NGAY_KY_HOP_DONG', $model->advanceProfile->hiringCompany->union->signing_contract_date);
	    
	    	$temp_file = tempnam(sys_get_temp_dir(), 'PHPWord');
	    	
	    		$document->save($temp_file);
		    	// Redirect output to a client’s web browser (.docx)
		    	header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
		    	header('Content-Disposition: attachment;filename="'.stringSafeFile($filename. ' ' . $model->full_name).'.'.$ext.'"');
		    	header('Cache-Control: max-age=0');
		    	readfile($temp_file); // or echo file_get_contents($temp_file);
		    	@unlink($temp_file); // remove temp file	    		
	    	}
	    	catch (Exception $ex)
	    	{
	    		throw new $ex;
	    	}	    	
    }  
}

?>
